﻿using Microsoft.AspNetCore.Http;
using System.Web;

namespace Service.Base
{
    public class UploadService : BaseService<TImage>, IUploadService
    {
        public UploadService(IUnitOfWorkService unitOfWorkService) : base(unitOfWorkService)
        {
        }

        public async Task<RM_Image> UploadReturnModel(IFormFile file, Enum_ImageSourceType sourceType)
        {
            try
            {
                var fname = file.FileName;
                if (await Any(o => o.Name == file.FileName))
                {
                    fname = string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(file.FileName), DateTime.Now.ToString("yyyyMMddHHmmssffffff"), Path.GetExtension(file.FileName));
                }
                fname = HttpUtility.UrlDecode(fname);
                var url = await LocalUpLoad(file, fname);
                var o = new TImage
                {
                    SourceType = sourceType,
                    Status = (int)Enum_BaseStatus.Working,
                    LinkCount = 1,
                    Url = url,
                    Name = fname
                };
                await Add(o);

                return new RM_Image { FileName = fname, Url = url };
            }
            catch (Exception ex)
            {
                await Console.Out.WriteLineAsync(ex.ToString());
                return null;
            }
        }

        public async Task<RM_ApiResult> AdminUpLoad(IFormFile file)
        {
            //检查文件类型
            //if (!file.ContentType.Contains("image"))
            //{
            //    return _ResultHelper.BuildError(Enum_SysAttributeType.Image.ErrorFormat);
            //}
            //检查文件大小
            if (file.Length > 1024 * 1024 * 1)
            {
                return _ResultHelper.BuildError(Enum_SysAttributeType.Image.ErrorLimit);
            }

            //上传图片
            var uploadResult = await UploadReturnModel(file, Enum_ImageSourceType.Admin);

            //检查上传结果
            if (uploadResult == null)
            {
                return _ResultHelper.BuildError(Enum_SysAttributeType.Image.UploadError);
            }

            return _ResultHelper.BuildSuccess(uploadResult);
        }

        public async Task<RM_ApiResult> FrontUpLoad(IFormFile file)
        {
            //检查文件类型
            //if (!file.ContentType.Contains("image"))
            //{
            //    return _ResultHelper.BuildError(Enum_SysAttributeType.Image.ErrorFormat);
            //}
            //检查文件大小
            if (file.Length > 1024 * 1024 * 1)
            {
                return _ResultHelper.BuildError(Enum_SysAttributeType.Image.ErrorLimit);
            }

            //上传图片
            var uploadResult = await UploadReturnModel(file, Enum_ImageSourceType.Front);

            //检查上传结果
            if (uploadResult == null)
            {
                return _ResultHelper.BuildError(Enum_SysAttributeType.Image.UploadError);
            }

            return _ResultHelper.BuildSuccess(uploadResult);
        }

        private static async Task<string> LocalUpLoad(IFormFile file, string fileName)
        {
            string directory = Path.Combine(AppSettings.GetConfig("PhysicalPath"), DateTime.Now.ToString("yyyy-MM"));

            if (!CommoHelper.IsExistDirectory(directory))
            {
                CommoHelper.CreateDir(directory);
            }

            var path = Path.Combine(directory, fileName);
            string urldir = DateTime.Now.ToString("yyyy-MM");
            string url = string.Format("/file/{0}/{1}", urldir, fileName);

            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            return url;
        }
    }
}